<?php

class MemberController extends BaseController {

    public function indexAction($requestData) {
    	Member::checkCookie();
    	
		if(!Member::isMemberLoggedIn()) {
			BaseController::forward('Member', 'login');
			return;
		}
		
		$this->data['member'] = Member::get($_SESSION['member']);
    }
    
    public function loginAction($requestData) {
    	if(Member::isMemberLoggedIn()) {
    		BaseController::forward('Member', 'index');
    	}
    	if(isset($requestData['login1'])) {
    		$errorMessage = 'Wrong Member ID and/or Password.';
    		$member = Member::get($requestData['login1'], "login");
    		$logs['data'] = sprintf("%s login", $requestData['login1']);
    		if($member->id > 0) {
    			if($member->password == md5($requestData['password'])) {
    				$_SESSION['member'] = $member->id;
		    		$logs['ext'] = "Success";
		    		if(isset($requestData['remember1'])) {
		    			Member::saveMemberCookie($member->id);
		    			$logs['ext'] .= ";remember";
		    		}
    				BaseController::redirect('../');
    			} else {
    				$logs['ext'] = "Failed";
    				$this->data['login_error'] = $errorMessage;
    			}
    		} else {
    			$logs['ext'] = "No such user";
    			$this->data['login_error'] = $errorMessage;
    		}
    		$log = new Log($logs);
    		$log->save();
    	}
    }
    
    public function registerAction($requestData) {
    	if(!isset($requestData['submit'])) {
    		BaseController::forward('Member', 'login');
    		return;
    	}
    	$member = new Member($requestData);
    	$member->password2 = isset($requestData['password2']) ? $requestData['password2'] : "";
    	$validation = $member->validate();
    	if(is_array($validation)) {
    		$this->data['registration_error'] = $validation[0];
    		unset($validation[0]);
    		foreach($validation as $error) {
    			$this->data['registration_error'] .= ", $error";
    		}
			BaseController::forward('Member', 'login');
    	} else {
    		$member->password = md5($member->password);
    		$member->save();
    		if(isset($requestData['remember'])) {
    			Member::saveMemberCookie($member->id);
    		}
    		$_SESSION['member'] = $member->id;
    		BaseController::redirect('../');
    	}
    }
    
    public function logoutAction($requestData) {
    	if(isset($_SESSION['member'])) {
	    	$logs['data'] = sprintf("Member %s logout", $_SESSION['member']);
	    	unset($_SESSION['member']);
	    	if(isset($_COOKIE['member'])) {
	    		setcookie("member", 0, time()-1, "/", str_replace('www', '', $_SERVER['HTTP_HOST']));
	    	}
	    	$log = new Log($logs);
	    	$log->save();
    	}
    	BaseController::forward('Member', 'login');
    }
    
    public function profileAction($requestData, $member=NULL) {
    	if($member == NULL) {
	    	$member = Member::get($requestData['arg0'], "login");
    	}
    	$this->data['member'] = $member;
    }
    
    public function allAction($requestData) {
    	
    }

}

?>